/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.delivery.api.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.MyOrderDto;
import com.yami.shop.bean.app.dto.StationDto;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.Station;
import com.yami.shop.bean.param.StationDetailParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.delivery.common.service.OrderSelfStationService;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.OrderVirtualInfoService;
import com.yami.shop.service.StationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author Lanhai
 */
@RestController
@RequestMapping("/p/station")
@Api(tags = "自提订单接口")
@AllArgsConstructor
public class StationController {

    private final MapperFacade mapperFacade;

    private final OrderService orderService;

    private final StationService stationService;

    private final OrderSelfStationService orderSelfStationService;

    private final OrderVirtualInfoService orderVirtualInfoService;

    @GetMapping("/getStationOrderByCode")
    @ApiOperation(value = "通过提货码获取自提订单", notes = "自提点输入提货码获取自提订单")
    @ApiImplicitParam(name = "code", value = "提货码", required = true, dataType = "String")
    public ServerResponseEntity<MyOrderDto> getStationOrderByCode(@RequestParam(value = "code", required = true) String code) {
        MyOrderDto myOrderDto = orderSelfStationService.getOrderByStationCode(SecurityUtils.getUser().getStationId(),
                SecurityUtils.getUser().getShopId(), code);
        return ServerResponseEntity.success(myOrderDto);
    }

    @GetMapping("/userstation")
    @ApiOperation("获取距离用户近的自提点")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lat", value = "纬度", required = true),
            @ApiImplicitParam(name = "lng", value = "经度", required = true),
            @ApiImplicitParam(name = "stationName", value = "自提点名字"),
            @ApiImplicitParam(name = "shopId", value = "店铺id")
    })
    public ServerResponseEntity<IPage<StationDetailParam>> getStationList(@RequestParam(value = "lat",required = false) Double lat,
                                                                    @RequestParam(value = "lng",required = false) Double lng,
                                                                    @RequestParam("stationName") String stationName,
                                                                    @RequestParam("shopId") Long shopId,
                                                                          PageParam page) {
        IPage<StationDetailParam> stationParams = stationService.getStationList(lat, lng, stationName, shopId, SecurityUtils.getUser().getUserId(), page);
        return ServerResponseEntity.success(stationParams);
    }

    @PutMapping("/orderStationByOrderNumber")
    @ApiOperation(value = "自提点提货", notes = "自提点提货操作")
    @ApiImplicitParam(name = "orderNumbers", value = "订单编号数组", required = true, dataType = "String")
    public ServerResponseEntity<Boolean> orderStationByOrderNumber(@RequestBody String orderNumbers) {
        List<String> orderNumberList = Arrays.asList(orderNumbers.split(","));
        return ServerResponseEntity.success(orderService.orderStationByOrderNumber(orderNumberList, null, SecurityUtils.getUser().getStationId()));
    }

    @GetMapping("/info")
    @ApiOperation(value = "自提点信息", notes = "查询自提点信息")
    public ServerResponseEntity<StationDto> getById() {
        Long stationId = SecurityUtils.getUser().getStationId();
        Station station = stationService.getStationInfoById(stationId);
        StationDto stationDto = mapperFacade.map(station, StationDto.class);
        stationDto.setStationId(station.getStationId());
        stationDto.setTimeDate(station.getTimeDate());
        return ServerResponseEntity.success(stationDto);
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改自提点", notes = "修改自提点信息")
    public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid StationDto stationDto) {
        Station station = mapperFacade.map(stationDto, Station.class);
        Long shopId = SecurityUtils.getUser().getShopId();
        station.setShopId(shopId);
        stationService.updateStation(station);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getStationIndexInfo")
    @ApiOperation(value = "自提点首页数据", notes = "获取自提点首页数据")
    public ServerResponseEntity<StationDto> getStationIndexInfo() {
        Long stationId = SecurityUtils.getUser().getStationId();
        Long shopId = SecurityUtils.getUser().getShopId();
        Station station = stationService.getStationInfoById(stationId);
        StationDto stationDto = new StationDto();
        stationDto.setStationId(station.getStationId());
        stationDto.setPic(station.getPic());
        stationDto.setStationName(station.getStationName());
        stationDto.setStationSalesDtoList(stationService.getStationSalesRecord(shopId, stationId));
        return ServerResponseEntity.success(stationDto);
    }

    @GetMapping("/orderListByStatus")
    @ApiOperation(value = "订单列表信息", notes = "根据订单状态获取订单列表信息，状态为0时获取所有订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败", dataType = "Integer"),
    })
    public ServerResponseEntity<IPage<MyOrderDto>> orderListByStatus(@RequestParam(value = "status") Integer status, PageParam<MyOrderDto> page) {
        Long stationId = SecurityUtils.getUser().getStationId();
        IPage<MyOrderDto> myOrderDtoIpage = orderService.orderListByStatus(page, status, stationId);
        return ServerResponseEntity.success(myOrderDtoIpage);
    }

    @GetMapping("/getCode")
    @ApiOperation(value = "自提点二维码信息", notes = "自提点二维码信息")
    public ServerResponseEntity<String> getCode() {
        Long stationId = SecurityUtils.getUser().getStationId();
        Station station = stationService.getStationInfoById(stationId);
        String code = station.getShopId() + "#station#" + stationId;
        return ServerResponseEntity.success(code);
    }

    @PutMapping("/orderWriteOffByOrderNumber")
    @ApiOperation(value = "虚拟商品订单核销操作", notes = "虚拟商品订单核销操作")
    public ServerResponseEntity<Boolean> orderWriteOffByOrderNumber(@RequestBody MyOrderDto myOrderDto) {
        String orderNumber = myOrderDto.getOrderNumber();
        Long stationId = SecurityUtils.getUser().getStationId();
        Long shopId = SecurityUtils.getUser().getShopId();
        if (StrUtil.isBlank(orderNumber)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        Order orderDb = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNumber, orderNumber)
                .eq(Order::getShopId, shopId)
                .eq(Order::getOrderMold,1));
        if (Objects.isNull(orderDb)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        return ServerResponseEntity.success(orderVirtualInfoService.orderWriteOffByOrderNumber(myOrderDto, orderDb, stationId));
    }
}
